package com.gitee.cui.client.sender;

import com.gitee.cui.client.client.ClientSession;
import com.gitee.cui.common.common.bean.User;
import com.gitee.cui.common.common.bean.msg.ProtoMsg;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 发送消息抽象类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/27 15:04
 **/
@Data
@Slf4j
public abstract class BaseSender {

    /**
     * 用户信息
     */
    private User user;

    /**
     * 用户session信息
     */
    private ClientSession session;

    public boolean isConnected() {
        if (session == null) {
            log.info("session is null");
            return false;
        }
        return session.isConnected();
    }

    public boolean isLogin() {
        if (session == null) {
            log.info("session is null");
            return false;
        }
        return session.isLogin();
    }

    public void sendMsg(ProtoMsg.Message message) {
        if (session == null || !isConnected()) {
            log.info("连接还未成功");
            return;
        }
        Channel channel = session.getChannel();
        ChannelFuture future = channel.writeAndFlush(message);
        future.addListener(listener -> {
            if (listener.isSuccess()) {
                // 发送成功
                sendSuccess(message);
            } else {
                // 发送失败
                sendFailed(message);
            }
        });
    }

    protected void sendFailed(ProtoMsg.Message message) {
        log.info("发送失败");
    }

    protected void sendSuccess(ProtoMsg.Message message) {
        log.info("发送成功");
    }
}
